package com.mall.mallapi.controller;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author: 谢君臣
 * @Date: 2022/7/21-16:16
 * @version: 1.0
 * @function:
 */
@RestController
@RequestMapping("/mallApi")
public class ApiController {

    @Resource
    private DiscoveryClient client;

    @GetMapping("/discovery")
    public Object discovery() {
        // 获取微服务列表的清单
        List<String> services = client.getServices();
        System.out.println("discovery=>services:" + services);

        // 得到一个具体的微服务信息,通过具体的微服务id，applicationName；
        List<ServiceInstance> instances = client.getInstances("gatewayServer");
        for (ServiceInstance instance : instances) {
            System.out.println(
                    instance.getHost() + "\t" + // 主机名称
                            instance.getPort() + "\t" + // 端口号
                            instance.getUri() + "\t" + // uri
                            instance.getServiceId() // 服务id
            );
        }
        return this.client;
    }
    @GetMapping({"/swagger-ui","swagger"})
    public List<Map<String,String>> getServerSwaggerUi(){
        List<Map<String,String>> resList = new LinkedList<>();
        List<String> services = client.getServices();
        for (String serviceName : services) {
            List<ServiceInstance> instances = client.getInstances(serviceName);
            for (ServiceInstance instance : instances) {
                Map<String,String> resMap = new HashMap<>();
                resMap.put("hostName",instance.getHost());
                resMap.put("port",String.valueOf(instance.getPort()));
                resMap.put("serviceId",instance.getServiceId());
                resMap.put("swaggerUrl",instance.getUri().toString()+"/swagger-ui/index.html");
                resList.add(resMap);
            }
        }
        return resList;
    }
}
